package com.sup.servlet;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sup.entity.User;

/**
 * Servlet implementation class ResgisterServlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static EntityManagerFactory emf;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init()
    {
    	emf = Persistence.createEntityManagerFactory("PersistenceUnit");
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.getServletContext().getRequestDispatcher("/register.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManager em = emf.createEntityManager();
		
		
		User newUser = new User();
		newUser.setAdmin(0);
		newUser.setName(request.getParameter("name"));
		newUser.setFirstname(request.getParameter("firstname"));
		newUser.setEmail(request.getParameter("email"));
		newUser.setPassword(request.getParameter("password"));
		
		
		em.getTransaction().begin();
	    em.persist(newUser);
	    em.getTransaction().commit();
	    em.close();
	}

}
